package ks.client.controllers;

import ks.client.UserContext;
import ks.client.ipc.Client;
import ks.client.lobby.Lobby;
import ks.client.processor.Processor;
import ks.framework.interfaces.IProcessMessage;

/**
 * On client-side, manage the request to initiate a connection to a remote 
 * server host.
 * <p>
 * This is an internal controller used by the KS framework code and that is why
 * it doesn't implement {@link IProcessMessage}. You will not need to modify this
 * class.
 * 
 * @author George Heineman
 */
public class ConnectController {

	/** Manages top-level communication via lobby root object. */
	Lobby lobby;
	
	/** 
	 * Connection controller needs to know the RoomGUI to manage its functionality.
	 * 
	 * @param room
	 */
	public ConnectController (Lobby lobby) {
		this.lobby = lobby;
	}

	/**
	 * Attempt to connect to the remote host as specified by this context
	 * object.
	 * <p>
	 * A successful completion of this method results in a properly configured
	 * Client object associated with this context that can be used for all
	 * future communication with the remote server.
	 * 
	 * @param context
	 * @return
	 */
	public boolean process(UserContext context) {
		
		// create client and ensure that a processor is constructed to be 
		// able to manage requests for the lobby
		Client client = new Client();
		client.setProcessor(new Processor(lobby));
		
		// this will initiate a request to start speaking in its own thread
		// We have to wait until later to determine whether that communication
		// had succeeded.
		client.connect(context.getHost(), context.getPort(), context.getUser(), context.getPassword(), context.getSelfRegister());
		
		// if we get here, we believe we have the right context
		context.setClient(client);
		
		// we can only say we are "attempting to connect" because we now must
		// wait for confirmation from the server that we have appropriate credentials
		lobby.append("Connecting to: " + context.getHost() + "@" + context.getPort());
		
		// we can't know success of this method as of yet, until the thread 
		// communicating to the server returns.
		return true;
	}

}
